﻿using AutoMapper;
using MediatR;
using Traceability.App.Api.Application.Command.Basic;
using Traceability.App.Model.DeepProcessing;
using Traceability.App.Model;
using Traceability.App.InfrasIntructure;
using Traceability.App.ErrorCount;
using Microsoft.EntityFrameworkCore;

public class AddBasicHandler : IRequestHandler<AddBasicCommand, ApiResult<int>>
{
    private readonly IBaseRepository<BasicModel> _basicRepo;
    private readonly IBaseRepository<DeepProcessingCompanyModel> _deepProcessRepo;
    private readonly IMapper _mapper;

    public AddBasicHandler(IBaseRepository<BasicModel> basicRepo,IBaseRepository<DeepProcessingCompanyModel> deepProcessRepo,IMapper mapper)
    {
        _basicRepo = basicRepo;
        _deepProcessRepo = deepProcessRepo;
        _mapper = mapper;
    }

    public async Task<ApiResult<int>> Handle(AddBasicCommand request, CancellationToken cancellationToken)
    {
        var res = new ApiResult<int>();

        // 检查生产批次是否重复
        var batchExists = await _basicRepo.GetAll().AnyAsync(c => c.Batch == request.Batch && !c.IsDeleted);
        if (batchExists)
        {
            res.Msg = "生产批次不能重复";
            res.Code = ApiEnum.Error;
            return res;
        }

      
        if (!string.IsNullOrEmpty(request.License)) 
        {
            var deepProcessCompany = await _deepProcessRepo.GetAll().FirstOrDefaultAsync(c => c.Batch == request.Batch && !c.IsDeleted);

            if (deepProcessCompany != null && string.IsNullOrEmpty(deepProcessCompany.LicenseNum))
            {
                // 将基础信息的 License 赋值给深加工企业的 LicenseNum
                deepProcessCompany.LicenseNum = request.License;
                await _deepProcessRepo.Update(deepProcessCompany);
            }
        }

        // 添加基础信息
        var model = _mapper.Map<BasicModel>(request);
        model.Creator = request.Creator;
        model.CreatorDate = DateTime.Now;

        var result = await _basicRepo.Add(model);
        res.Datas = result;
        res.Code = result > 0 ? ApiEnum.Success : ApiEnum.Fail;
        res.Msg = result > 0 ? "添加基本信息成功" : "添加基本信息失败";

        return res;
    }
}